
import { cwbbJson } from "../data/cwbb.js"
import { fillInputDone } from "../../common.js"

async function fillcwbb({ saasData }) {
  let isYearReport = saasData.isYearReport;
  let ins = saasData.data.openParams.taxInfo.institution === '2013' ? 'xqykjzz' : 'qykjzz';
  let sheet = saasData.sheet;
  let inputData = '';

  if (isYearReport) {
    inputData = saasData.data.openParams.inputData.data[sheet];
    let lastYearData = saasData.data.openParams.inputData.lastYearData[sheet];
    if (sheet === 'profit' || sheet === 'cash') {
      inputData = inputData.map((item, index) => {
        let obj = {};
        obj.colValue1 = ins === 'qykjzz' ? item.colValue3 : item.colValue1;
        obj.colValue2 = ins === 'qykjzz' ? lastYearData[index].colValue3 : lastYearData[index].colValue1;
        obj.reportItemRowNbr = lastYearData[index].reportItemRowNbr;
        return obj;
      });
    }
  } else {
    inputData = saasData.data.openParams.inputData.data[sheet];
  }

  if (['balance', 'profit', 'cash'].includes(sheet)) {
    try {
      if (ins === 'qykjzz') throw new Error('暂不支持企业会计准则财务报表填报，请持续关注')
      let data = getinputData(inputData, ins, sheet, isYearReport);

      // let iframeWindow;
      // let iframeWindow = $('#mainIframe')[0].contentWindow;
      let contentiframe = $('#contentiframe')[0].contentWindow;
      let iframeWindow = contentiframe.$('#mainIframe')[0].contentWindow;

      for (let key in data) {
        let value = Number.parseFloat(data[key]).toFixed(2) || '0.00';
        if (iframeWindow.$(`[name$="${key}"]`).length != 0) {
          iframeWindow.$(`[name$="${key}"]`).val(value).trigger('change');
        } else {
          throw new Error('未找到对应的页面')
        }
      }

      fillInputDone({
        tax: 'cwbb', // 税种
        success: true, // 是否成功
        message: "财务报表-填报完成", // 文案
      })
    } catch (e) {
      console.log(e);
      fillInputDone({
        tax: 'cwbb', // 税种
        success: false, // 是否成功
        message: "财务报表-填报失败，请联系技术人员", // 文案
      })
    }
  }
}

function getinputData(inputData, ins, sheet, isYearReport) {
  let vkObj = cwbbJson[ins][sheet];
  let obj = {};
  for (let k in vkObj) {
    let v = vkObj[k];
    let vArr = v.split('_');
    let reportItemRowNbr = vArr[0];
    let item = inputData.find(item => parseInt(item.reportItemRowNbr) === parseInt(reportItemRowNbr));
    obj[k] = item[vArr[1]] || "0.00";
  }
  return obj;
}

function getTaxCwbbinstitutionCode() {
  if (window.location.href.includes('/portal/index.do')) {
    // 重写goUrl
    let goUrl1 = window.goUrl;
    window.goUrl = (url, appbh) => {
      let institutionCode = '';
      let tds = $('#sxtable tbody tr>td:nth-child(2)');
      if (tds.length > 0) {
        let td = Array.from(tds).find(item => {
          return $(item).text().includes('财务报表');
        })
        if (td) {
          let text = $(td).text();
          if (text.includes('适用执行小企业会计准则的企业')) {
            institutionCode = 1;
          }
          if (text.includes('适用非执行')) {
            institutionCode = 2;
          }
        }
      }
      window.postMessage(
        {
          event: 'fixTaxGovInfo',
          data: {
            institutionCode
          }
        }
      )
      goUrl1(url, appbh);
    }
  }
  if (window.location.href.includes('/portal/include.do')) {
    let timer = setInterval(() => {
      try {
        let contentiframe = $('#contentiframe')[0].contentWindow;
        let iframeWindow = contentiframe.$('#mainIframe')[0].contentWindow;
        if (!iframeWindow.jumpToSBB) {
          throw new Error('jumpToSBB')
        }
        let jumpToSBB1 = iframeWindow.jumpToSBB;
        iframeWindow.jumpToSBB = function () {
          let institutionCode = ''
          let input = iframeWindow.$('.billContentBox > .topbox > .rightbox > .type');
          let text = input.text();
          if (text.includes('适用执行小企业会计准则的企业')) {
            institutionCode = 2;
            window.postMessage(
              {
                event: 'fixTaxGovInfo',
                data: {
                  institutionCode
                }
              }
            )
          }
          jumpToSBB1.apply(iframeWindow, arguments);
          timer = '';
        }
        clearInterval(timer);
        timer = '';
      } catch (e) {
        console.log(e);
        return false;
      }
    }, 1000);
  }
}

export {
  fillcwbb,
  getTaxCwbbinstitutionCode
}